# core/db_client.py
import pymysql
from pymysql.cursors import DictCursor
from utils.log_utils import log
from utils.config_util import ConfigUtil


class DBClient:
    def __init__(self):
        self.config = ConfigUtil.get_db_config()
        self.conn = None
        self.cursor = None

    def connect(self):
        """连接数据库"""
        try:
            self.conn = pymysql.connect(
                host=self.config["host"],
                port=self.config["port"],
                user=self.config["user"],
                password=self.config["password"],
                database=self.config["database"],
                charset="utf8mb4"
            )
            self.cursor = self.conn.cursor(cursor=DictCursor)  # 返回字典格式
            log.info("数据库连接成功")
        except Exception as e:
            log.error(f"数据库连接失败: {e}")
            raise

    def query_one(self, sql, args=None):
        """查询单条数据"""
        try:
            self.cursor.execute(sql, args)
            result = self.cursor.fetchone()
            log.info(f"执行查询SQL: {sql}, 参数: {args}, 结果: {result}")
            return result
        except Exception as e:
            log.error(f"查询失败: {e}")
            self.conn.rollback()
            raise

    def close(self):
        """关闭连接"""
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()
        log.info("数据库连接已关闭")
